package com.dries.security.rbac.service.impl;

import com.dries.security.rbac.service.IRbacService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Set;

/**
 * @Description:
 * @Author ZSY
 * @createTime 2020/9/22 15:03
 */
@Component("rbacService")
public class RbacServiceImpl implements IRbacService {

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {

        Object principal = authentication.getPrincipal();
        boolean hasPermission = false;

        if (principal instanceof UserDetails) {

            String username = ((UserDetails) principal).getUsername();

            // 读取用户所拥有权限的所以URL
            Set<String> urls = new HashSet<>();

            for (String url : urls) {
                if (antPathMatcher.match(url, request.getRequestURI())) {
                    hasPermission = true;
                    break;
                }
            }
        }

        return hasPermission;
    }
}
